package com.szy.redstonemcu;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.input.Keyboard;

import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class EditScreen extends GuiScreen implements ButtonClickListener {
    int guiLeft;
    int guiTop;

    int xSize=255;
    int ySize=210;

    private final int MAX_LINES=15;
    public int activeFieldIndex=0;
    public ArrayList<GuiTextField> fields=new ArrayList<>();

    public ArrayList<GuiTextField> resultFields=new ArrayList<>();

    public ArrayList<String> codes=new ArrayList<>();

    public final static int BUTTON_ID_BUILD=20;
    public final static int BUTTON_ID_RUN=21;
    public final static int BUTTON_ID_PAUSE=22;
    public final static int BUTTON_ID_RESUME=23;
    public BlockPos pos=new BlockPos(0,0,0);

    public int firstLineNumber=0;
    public EditScreen(){

    }
    public EditScreen(String code, BlockPos pos){
        String[] codeSplit=code.trim().split("\n");
        codes.addAll(Arrays.asList(codeSplit));
        this.pos=pos;
    }

    public String getCodeLine(int lineNumber){
        while(codes.size() <= lineNumber){
            codes.add("");
        }
        return codes.get(lineNumber);
    }
    public void setCodeLine(int lineNumber,String s){
        while(codes.size() <= lineNumber){
            codes.add("");
        }
        codes.set(lineNumber,s);
    }
    public void drawAllLines(){
        for(int i=0;i<MAX_LINES;i++){
            fields.get(i).setText(getCodeLine(firstLineNumber+i));
        }
    }
    @Override
    public void initGui() {
        super.initGui();
        this.guiLeft = (this.width - this.xSize) / 2;
        this.guiTop = (this.height - this.ySize) / 2;

        Keyboard.enableRepeatEvents(true);
        for(int i=0;i<MAX_LINES;i++){
            GuiTextField field=new GuiTextField(i,this.fontRenderer,guiLeft+23,guiTop+7+i*10,230,10);
            field.setMaxStringLength(64);
            field.setEnableBackgroundDrawing(false);
            field.setFocused(false);
            field.setText(getCodeLine(i));

            //field.setTextColor(0xffffff);
            fields.add(field);
        }
        fields.get(0).setFocused(true);

        addButton(new CallbackButton(BUTTON_ID_BUILD,guiLeft+179,guiTop+162,33,20,"Build").setListener(this));
        addButton(new CallbackButton(BUTTON_ID_RUN,guiLeft+216,guiTop+162,33,20,"Run").setListener(this));
        addButton(new CallbackButton(BUTTON_ID_PAUSE,guiLeft+179,guiTop+184,33,20,"Pause").setListener(this));
        addButton(new CallbackButton(BUTTON_ID_RESUME,guiLeft+216,guiTop+184,33,20,"Resume").setListener(this));

        for(int i=0;i<4;i++){
            GuiTextField field=new GuiTextField(30,this.fontRenderer,guiLeft+7,guiTop+163+i*10,167,10);
            field.setMaxStringLength(48);
            field.setEnableBackgroundDrawing(false);
            field.setFocused(false);
            field.setText("");
            resultFields.add(field);
        }


    }
    @Override
    public void onGuiClosed()
    {
        Keyboard.enableRepeatEvents(false);
        this.mc.ingameGUI.getChatGUI().resetScroll();
    }

    @Override
    public void updateScreen()
    {
        for(GuiTextField field:fields){
            field.updateCursorCounter();
        }

    }

    public static int KEY_CODE_ESC=1;
    public static int KEY_CODE_TAB=15;
    public static int KEY_CODE_UP=200;
    public static int KEY_CODE_DOWN=208;
    public static int KEY_CODE_ENTER=28;

    public static int KEY_CODE_BACKSPACE=14;
    @Override
    protected void keyTyped(char typedChar, int keyCode) throws IOException {
        if(keyCode != KEY_CODE_ESC){
            if(keyCode == KEY_CODE_TAB){
                fields.get(activeFieldIndex).textboxKeyTyped(' ', 32);
                fields.get(activeFieldIndex).textboxKeyTyped(' ', 32);
                fields.get(activeFieldIndex).textboxKeyTyped(' ', 32);
                fields.get(activeFieldIndex).textboxKeyTyped(' ', 32);
            }else if(keyCode == KEY_CODE_UP) {
                if(activeFieldIndex>0){
                    int currentCursor=fields.get(activeFieldIndex).getCursorPosition();
                    fields.get(activeFieldIndex).setFocused(false);
                    activeFieldIndex--;
                    fields.get(activeFieldIndex).setFocused(true);
                    fields.get(activeFieldIndex).setCursorPosition(currentCursor);
                } else if (firstLineNumber > 0) {
                    firstLineNumber--;
                    drawAllLines();
                }
            } else if (keyCode == KEY_CODE_DOWN) {
                if(activeFieldIndex < MAX_LINES-1){
                    int currentCursor=fields.get(activeFieldIndex).getCursorPosition();
                    fields.get(activeFieldIndex).setFocused(false);
                    activeFieldIndex++;
                    fields.get(activeFieldIndex).setFocused(true);
                    fields.get(activeFieldIndex).setCursorPosition(currentCursor);
                }else{
                    firstLineNumber++;
                    drawAllLines();
                }

            } else if (keyCode == KEY_CODE_ENTER) {
                String originLine=getCodeLine(firstLineNumber+activeFieldIndex);
                int cursor=fields.get(activeFieldIndex).getCursorPosition();
                String newLine1=originLine.substring(0,cursor);
                String newLine2=originLine.substring(cursor);
                codes.add(firstLineNumber+activeFieldIndex+1,newLine2);
                setCodeLine(firstLineNumber+activeFieldIndex,newLine1);
                if(activeFieldIndex == MAX_LINES-1){
                    firstLineNumber++;
                }else{
                    fields.get(activeFieldIndex).setFocused(false);
                    activeFieldIndex++;
                    fields.get(activeFieldIndex).setFocused(true);
                }
                drawAllLines();
                fields.get(activeFieldIndex).setCursorPosition(0);
            }else if (keyCode == KEY_CODE_BACKSPACE && fields.get(activeFieldIndex).getCursorPosition() == 0) {
                if(activeFieldIndex+firstLineNumber > 0){
                    String line1=getCodeLine(activeFieldIndex+firstLineNumber-1);
                    int cursor=line1.length();
                    String line2=getCodeLine(activeFieldIndex+firstLineNumber);
                    setCodeLine(activeFieldIndex+firstLineNumber-1,line1+line2);
                    codes.remove(activeFieldIndex+firstLineNumber);

                    if(activeFieldIndex == 0){
                        firstLineNumber--;
                        drawAllLines();
                        fields.get(0).setCursorPosition(cursor);
                    }else{
                        fields.get(activeFieldIndex).setFocused(false);
                        activeFieldIndex--;
                        fields.get(activeFieldIndex).setFocused(true);
                        drawAllLines();
                        fields.get(activeFieldIndex).setCursorPosition(cursor);
                    }
                }
            }else{
                fields.get(activeFieldIndex).textboxKeyTyped(typedChar, keyCode);
                setCodeLine(firstLineNumber+activeFieldIndex,fields.get(activeFieldIndex).getText());
            }

        }else{
            saveCode();
        }
//        for(int i=codes.size();i<=activeFieldIndex+firstLineNumber;i++){
//            codes.add("");
//        }
//        setCodeLine(activeFieldIndex+firstLineNumber,fields.get(activeFieldIndex).getText());

        super.keyTyped(typedChar, keyCode);
    }

    @Override
    protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
        super.mouseClicked(mouseX, mouseY, mouseButton);
        for(int i=0;i<MAX_LINES;i++){
            if(fields.get(i).mouseClicked(mouseX, mouseY, mouseButton)){
                if(i==activeFieldIndex){
                    break;
                }
                fields.get(activeFieldIndex).setFocused(false);
                activeFieldIndex=i;
                break;
            }
        }
    }

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks)
    {
        ResourceLocation background=new ResourceLocation(RedstoneMCU.MODID,"textures/gui/mcu.png");
        Minecraft.getMinecraft().getTextureManager().bindTexture(background);
        GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
        drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
        //drawRect(10, 10, 10, 10, Integer.MIN_VALUE);

        //this.fields.get(0).drawTextBox();
        for(GuiTextField field:fields){
            field.drawTextBox();
        }
        for(GuiTextField field:resultFields){
            field.drawTextBox();
        }
//        ITextComponent itextcomponent = this.mc.ingameGUI.getChatGUI().getChatComponent(Mouse.getX(), Mouse.getY());
//
//        if (itextcomponent != null && itextcomponent.getStyle().getHoverEvent() != null)
//        {
//            this.handleComponentHover(itextcomponent, mouseX, mouseY);
//        }
        for(int i=0;i<MAX_LINES;i++){
            fontRenderer.drawString(i+1+firstLineNumber+"",guiLeft+8,guiTop+7+i*10, Color.WHITE.getRGB(),true);
        }

        super.drawScreen(mouseX, mouseY, partialTicks);
    }

    @Override
    public boolean doesGuiPauseGame()
    {
        return false;
    }

    public void showResult(String s){
        String[] lines=s.trim().split("\n");
        for(GuiTextField field:resultFields){
            field.setText("");
        }
        for(int i=0;i<4 && i<lines.length;i++){
            resultFields.get(i).setText(lines[i]);
        }
    }
    private String getCodeString(){
        StringBuilder s= new StringBuilder();
        for(String line:codes){
            s.append(line).append("\n");
        }
        return s.toString();
    }
    public void saveCode(){

        RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_SAVE_CODE,getCodeString()));
    }
    @Override
    public void onClick(int buttonID) {
        RedstoneMCU.logger.info("button "+buttonID+" clicked");
        switch (buttonID){
            case BUTTON_ID_BUILD:
                saveCode();
                RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_ASSEMBLE_CODE,getCodeString()));
                break;
            case BUTTON_ID_RUN:
                RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_RESET_RUN));
                break;
            case BUTTON_ID_PAUSE:
                RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_PAUSE));
                break;
            case BUTTON_ID_RESUME:
                RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_RESUME));
                break;
        }
    }
}
